﻿(function ($) {
    function getGridId(buttonId) {
        return buttonId.split("_")[0];
    }

    function setGridButtonStatus(target) {
        //alert("set button status " + gridId);
        var rows = $(target).datagrid('getSelections');
        selectedCount = rows.length;
        //alert(selectedCount);
        $("#" + target.id + "_btnCopy").linkbutton(selectedCount == 1 ? "enable" : "disable");
        $("#" + target.id + "_btnModify").linkbutton(selectedCount == 1 ? "enable" : "disable");
        $("#" + target.id + "_btnDelete").linkbutton(selectedCount > 0 ? "enable" : "disable");
        var opts = $(target).data("detailgrid");
        if (opts.onSetButtonStatus) {
            opts.onSetButtonStatus(selectedCount);
        }
    }

    function getSelectedList(gridId) {
        var opts = $(gridId).data("detailgrid");
        var rows = $(gridId).datagrid('getSelections');
        var ids = [];
        for (var i = 0; i < rows.length; i++) {
            ids.push(rows[i][opts.guidColumn]);
        }
        return ids.join(',');
    }

    function executeAction(target, actionCode) {
        var gridId = getGridId(target.id);
        var opts = $("#" + gridId).data("detailgrid");
        var bizName = opts.bizName;
        var actionName = "";
        var selectedList = "";
        switch (actionCode) {
            case "add":
                actionName = opts.operationAddText;
                break;
            case "copy":
                actionName = opts.operationAddText;
                selectedList = getSelectedList("#" + gridId);
                break;
            case "modify":
                actionName = opts.operationModifyText;
                selectedList = getSelectedList("#" + gridId);
                break;
            case "delete":
                actionName = opts.operationDeleteText;
                selectedList = getSelectedList("#" + gridId);
                break;
        }
        opts.onAction(actionCode, actionName, bizName, selectedList);
    }

    function doubleClickGridRow(rowIndex, rowData) {
        var gridId = getGridId(this.id);
        var opts = $("#" + gridId).data("detailgrid");
        var bizName = opts.bizName;
        if (opts.onDblClick) {
            opts.onDblClick(bizName, rowData[opts.nameColumn], rowData[opts.guidColumn]);
        }
    }

    function onGridResize(width, height) {
        //        alert("grid resized to " + width + "," + height);
    }

    $.fn.detailgrid = function (options, param) {
        if (typeof options == "string") {
            if ($.fn.detailgrid.methods[options])
                return $.fn.detailgrid.methods[options](this, param);
            else {
                return $(this).datagrid(options, param);
            }
        }

        options = options || {};
        return this.each(function () {
            var gridId = '#' + this.id;
            var state = $(this).data("detailgrid");
            var opts;
            if (state) {
                opts = $.extend(state.options, options);
            } else {
                opts = $.extend({}, $.fn.detailgrid.defaults, $.fn.detailgrid.parseOptions(this), options);
                state = $(this).data("detailgrid", opts);
                var frzCols = opts.frozenColumns;
                if (opts.allowCheckbox) {
                    if (frzCols == undefined)
                        frzCols = [];
                    frzCols.push([{ field: 'ck', checkbox: true}]);
                }
                //$(this).datagrid({
                opts = $.extend(opts, {
                    fitColumns: true,
                    rownumbers: true,
                    frozenColumns: frzCols,
                    loadMsg: '数据装载中......',
                    onSelect: function () { setGridButtonStatus(this); },
                    onUnselect: function () { setGridButtonStatus(this); },
                    onSelectAll: function () { setGridButtonStatus(this); },
                    onUnselectAll: function () { setGridButtonStatus(this); }
                });

                var tools = [];
                if (opts.allowAdd) {
                    tools.push({
                        id: this.id + '_btnAdd',
                        text: opts.operationAddText,
                        iconCls: 'icon-add',
                        enable: false,
                        handler: function () { executeAction(this, "add"); }
                    });
                }
                if (opts.allowCopy) {
                    tools.push({
                        id: this.id + '_btnCopy',
                        text: opts.operationCopyText,
                        iconCls: 'icon-copy',
                        enable: false,
                        handler: function () { executeAction(this, "copy"); }
                    });
                }
                if (opts.allowEdit) {
                    tools.push({
                        id: this.id + '_btnModify',
                        text: opts.operationModifyText,
                        iconCls: 'icon-edit',
                        disabled: true,
                        handler: function () { executeAction(this, "modify"); }
                    });
                }
                if (opts.allowDelete) {
                    tools.push({
                        id: this.id + '_btnDelete',
                        text: opts.operationDeleteText,
                        iconCls: 'icon-remove',
                        disabled: true,
                        handler: function () { executeAction(this, "delete"); }
                    });
                }
                if (opts.extTools)
                    tools = tools.concat(opts.extTools);
                if (tools.length > 0)
                //$(this).datagrid({ toolbar: tools });
                    opts = $.extend(opts, { toolbar: tools });
                $(this).datagrid(opts);
                //$(this).datagrid("loadData", { total: 0, rows: [] });
            }

            //            var gridPanel = $(this).datagrid("getPanel");
            //            gridPanel.panel({ onResize: onGridResize });

            var pager = $(this).datagrid(opts).datagrid("getPager");
            $(pager).pagination({
                showPageList: false,
                pageSize: opts.pageSize,
                onSelectPage: opts.onSelectPage
            });
            //            if (opts.onSelectPage) {
            //                pager.onSelectPage = opts.onSelectPage;
            //            }
            $(this).bind("_buttonstatus", setGridButtonStatus(this));
            setGridButtonStatus(this);

            //$(this).bind("_resize", function () { alert("resize"); });
        });
    };

    $.fn.detailgrid.defaults = {
        title: '查询结果',
        iconCls: 'icon-detail',
        width: 'auto',
        height: 'auto',
        left: null,
        top: null,
        fit: true,
        pageSize: 10,
        pagination: true,
        allowCheckbox: true,
        allowAdd: true,
        allowEdit: true,
        allowCopy: false,
        allowDelete: true,
        operationAddText: '新增',
        operationModifyText: '修改',
        operationCopyText: '复制',
        operationDeleteText: '删除',
        content: null, // the body content if specified
        collapsible: false,
        collapsed: false,
        bizName: '',
        guidColumn: '',
        nameColumn: '',
        href: null,
        onLoad: function () { },
        onAction: function (actionCode, actionName, bizName, dataList) { },
        onDblClickRow: doubleClickGridRow,
        onDblClick: function (bizName, dataName, dataGuid) { },
        onResize: onGridResize,
        onSetButtonStatus: undefined
    };

    $.fn.detailgrid.parseOptions = function (target) {
        var t = $(target);
        return $.extend({}, $.fn.datagrid.parseOptions(target), {
            bizName: (t.attr("bizName") ? t.attr("collapsed") == "true" : undefined),
            guidColumn: (t.attr("guidColumn") || undefined),
            nameColumn: (t.attr("nameColumn") || undefined)
        });
    };

    function convertXmlStringToGridJson(xmlString, totalNodeName, matchNodeName, fieldList) {
        var totalRecord = 10;
        try {
            var xmlData = utility.xml.convertXmlStringToDoc(xmlString);
            totalRecord = xmlData.find(totalNodeName).text();
            var dataList = xmlData.find(matchNodeName);
            var records = [];
            if (fieldList.length > 0 && dataList.length > 0) {
                dataList.each(function (i, n) {
                    var record = {};
                    for (var i in fieldList) {
                        //record = $.extend( record, { fields[i] : $(n).find(fields[i]).text()});
                        record[fieldList[i]] = $(n).find(fieldList[i]).text();
                    }
                    records.push(record);
                });
            }
            return { total: totalRecord, rows: records };
        }
        catch (e) {
            return { total: 0, rows: [] };
        }
    }

    $.fn.detailgrid.methods = {
        queryTemplate: function (jq) { return queryXmlTemplate; },
        loadXmlString: function (jq, ops) {
            return $(jq).datagrid("loadData", convertXmlStringToGridJson(ops.xml, ops.totalNode, ops.dataNode, $(jq).datagrid("getColumnFields")));
        }
    };
})(jQuery);